// 获取所有导航链接和内容区域
const navLinks = document.querySelectorAll('.nav-link');
const contents = document.querySelectorAll('.content');

// 为每个导航链接添加点击事件处理函数
navLinks.forEach((link) => {
    link.addEventListener('click', function (e) {
        e.preventDefault();

        // 移除所有导航链接的 active 类
        navLinks.forEach((navLink) => {
            navLink.classList.remove('active');
        });

        // 添加当前点击链接的 active 类
        this.classList.add('active');

        // 隐藏所有内容区域
        contents.forEach((content) => {
            content.classList.remove('active');
        });

        // 获取目标内容区域的ID
        const targetId = this.dataset.target;
        // 根据ID查找目标内容区域
        const target = document.getElementById(targetId);

        if (target) {
            // 如果找到了目标内容区域，则添加 active 类
            target.classList.add('active');

            // 根据点击的不同标签，向后端发送对应请求
            switch (targetId) {
                case 'content1':
                    fetch('searchAllReserve')
                        .then((response) => {
                            if (!response.ok) {
                                throw new Error('Network response was not ok');
                            }
                            return response.json();
                        })
                        .then((data) => {
                            const tableBody = document.querySelector('#content1 table tbody');
                            tableBody.innerHTML = '';

                            // 检查并创建表头
                            const tableHeader = document.querySelector('#content1 table thead tr');
                            if (!tableHeader) {
                                const headerRow = document.createElement('tr');
                                const headerCells = ['预约编号', '教室编号', '教室名称', '用户编号', '用户姓名', '预约日期', '预约时间', '操作'];
                                headerCells.forEach((headerText) => {
                                    const th = document.createElement('th');
                                    th.textContent = headerText;
                                    headerRow.appendChild(th);
                                });
                                const thead = document.createElement('thead');
                                thead.appendChild(headerRow);
                                document.querySelector('#content1 table').appendChild(thead);
                            }

                            if (Array.isArray(data)) {
                                data.forEach((reservation) => {
                                    const row = document.createElement('tr');
                                    const reservationIdCell = document.createElement('td');
                                    reservationIdCell.textContent = reservation.reservation_id;
                                    const classroomIdCell = document.createElement('td');
                                    classroomIdCell.textContent = reservation.classroom_id;
                                    const classroomNameCell = document.createElement('td');
                                    classroomNameCell.textContent = reservation.classroomName;
                                    const userIdCell = document.createElement('td');
                                    userIdCell.textContent = reservation.user_id;
                                    const userNameCell = document.createElement('td');
                                    userNameCell.textContent = reservation.userName;
                                    const dateCell = document.createElement('td');
                                    dateCell.textContent = reservation.date;
                                    const timeCell = document.createElement('td');
                                    timeCell.textContent = reservation.time;

                                    const approveButton = document.createElement('button');
                                    approveButton.className = 'approveButton';
                                    approveButton.dataset.reservationId = reservation.reservation_id;
                                    approveButton.textContent = '通过';

                                    // 为“通过”按钮添加点击事件处理程序
                                    approveButton.addEventListener('click', function () {
                                        const reservationId = this.dataset.reservationId;
                                        // 使用fetch发送POST请求（假设后端接口为/approveReservation）
                                        fetch('approveReservation?reservationId=${reservationId}', {
                                            method: 'GET',
                                            headers: {
                                                'Content-Type': 'application/json'
                                            },

                                        })
                                            .then(response => {
                                                if (!response.ok) {
                                                    throw new Error('Network response was not ok');
                                                }
                                                return response.text();
                                            })
                                            .then(message => {
                                                if (message.includes('成功')) {
                                                    alert('审批通过成功');
                                                } else {
                                                    alert('审批通过失败：' + message);
                                                }
                                            })
                                            .catch(error => {
                                                console.error('审批通过请求出错：', error);
                                                alert('审批通过请求出错，请稍后重试');
                                            });
                                    });


                                    const rejectButton = document.createElement('button');
                                    rejectButton.className = 'rejectButton';
                                    rejectButton.dataset.reservationId = reservation.reservation_id;
                                    rejectButton.textContent = '驳回';

                                    const operationCell = document.createElement('td');
                                    operationCell.appendChild(approveButton);
                                    operationCell.appendChild(rejectButton);

                                    row.appendChild(reservationIdCell);
                                    row.appendChild(classroomIdCell);
                                    row.appendChild(classroomNameCell);
                                    row.appendChild(userIdCell);
                                    row.appendChild(userNameCell);
                                    row.appendChild(dateCell);
                                    row.appendChild(timeCell);
                                    row.appendChild(operationCell);

                                    tableBody.appendChild(row);
                                });
                            } else {
                                console.error('后端返回数据格式不正确');
                            }
                        })
                        .catch((error) => {
                            console.error('获取内容1数据时出错：', error);
                        });
                    break;
                case 'content2':
                    fetch('ApprovalRecords')
                        .then((response) => {
                            if (!response.ok) {
                                throw new Error('Network response was not ok');
                            }
                            return response.json();
                        })
                        .then((data) => {
                            const content2Div = document.getElementById('content2');
                            const table = content2Div.querySelector('#approvalRecordsTable');
                            const tbody = table.querySelector('tbody');
                            tbody.innerHTML = '';

                            // 检查并创建表头
                            const tableHeader = table.querySelector('thead tr');
                            if (!tableHeader) {
                                const headerRow = document.createElement('tr');
                                const headerCells = ['预约编号', '用户ID', '教室编号', '预约日期', '预约时间', '状态', '操作人'];
                                headerCells.forEach((headerText) => {
                                    const th = document.createElement('th');
                                    th.textContent = headerText;
                                    headerRow.appendChild(th);
                                });
                                const thead = document.createElement('thead');
                                thead.appendChild(headerRow);
                                table.appendChild(thead);
                            }

                            if (Array.isArray(data)) {
                                data.forEach((record) => {
                                    const row = document.createElement('tr');
                                    const reservationIdCell = document.createElement('td');
                                    reservationIdCell.textContent = record.reservation_id;
                                    const userIdCell = document.createElement('td');
                                    userIdCell.textContent = record.user_id;
                                    const classroomIdCell = document.createElement('td');
                                    classroomIdCell.textContent = record.classroom_id;
                                    const dateCell = document.createElement('td');
                                    dateCell.textContent = record.date;
                                    const timeCell = document.createElement('td');
                                    timeCell.textContent = record.time;
                                    const statusCell = document.createElement('td');
                                    statusCell.textContent = record.status;
                                    const operatorCell = document.createElement('td');
                                    operatorCell.textContent = record.operator;

                                    row.appendChild(reservationIdCell);
                                    row.appendChild(userIdCell);
                                    row.appendChild(classroomIdCell);
                                    row.appendChild(dateCell);
                                    row.appendChild(timeCell);
                                    row.appendChild(statusCell);
                                    row.appendChild(operatorCell);

                                    tbody.appendChild(row);
                                });
                            } else {
                                console.error('后端返回数据格式不正确');
                            }
                        })
                        .catch((error) => {
                            console.error('获取内容2数据时出错：', error);
                        });
                    break;
                case 'content3':
                    // // 发送fetch请求，这里不需要处理返回数据的逻辑，因为后端直接跳转页面
                    // fetch('classroom')
                    //     .then((response) => {
                    //         if (!response.ok) {
                    //             throw new Error('Network response was not ok');
                    //         }
                    //         // 返回一个成功的Promise，因为不需要处理返回数据，只要请求成功就行
                    //         return Promise.resolve();
                    //     })
                    //     .catch((error) => {
                    //         console.error('获取内容3数据时出错：', error);
                    //         // 这里可以根据需求添加一些错误处理逻辑，比如给用户提示等
                    //         alert('加载教室页面失败，请稍后重试');
                    //     });
                    break;
                case 'content4':
                    fetch('/fetchContent4Data')
                        .then((response) => response.json())
                        .then((data) => {
                            // 假设后端返回的数据格式如下，根据实际情况调整
                            const { contentText } = data;
                            document.getElementById('content4').textContent = contentText;
                        })
                        .catch((error) => {
                            console.error('获取内容4数据时出错：', error);
                        });
                    break;
                case 'content5':
                    fetch('/fetchContent5Data')
                        .then((response) => response.json())
                        .then((data) => {
                            // 假设后端返回的数据格式如下，根据实际情况调整
                            const { contentText } = data;
                            document.getElementById('content5').textContent = contentText;
                        })
                        .catch((classError) => {
                            console.error('获取内容5数据时出错：', classError);
                        });
                    break;
            }
        }
    });
});

